<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>待办事项管理</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4A90E2',
                        secondary: '#6BBBF7',
                        accent: '#E53E3E',
                        neutral: '#F3F4F6',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .task-complete {
                @apply line-through text-gray-400;
            }
            .task-incomplete::before {
                content: '';
                @apply inline-block w-2 h-2 bg-accent rounded-full mr-2;
            }
            .gradient-bg {
                background: linear-gradient(135deg, #E6F4FF 0%, #FFFFFF 100%);
            }
        }
    </style>
</head>
<body class="font-inter min-h-screen gradient-bg flex flex-col">
    <header class="w-full py-6 px-4 md:px-8 bg-white/80 backdrop-blur-sm shadow-sm">
        <div class="max-w-6xl mx-auto">
            <h1 class="text-[clamp(1.75rem,3vw,2.5rem)] font-bold text-gray-800">
                <i class="fa fa-check-square-o mr-2 text-primary"></i>待办事项管理
            </h1>
        </div>
    </header>

    <main class="flex-grow w-full px-4 md:px-8 py-8">
        <div class="max-w-6xl mx-auto bg-white rounded-xl shadow-md overflow-hidden">
            <div class="flex flex-col md:flex-row">
                <!-- 左侧：添加任务区域 -->
                <div class="p-6 md:p-8 border-b md:border-b-0 md:border-r border-gray-100 w-full md:w-1/3">
                    <h2 class="text-xl font-semibold text-gray-700 mb-4 flex items-center">
                        <i class="fa fa-plus-circle text-primary mr-2"></i>添加新任务
                    </h2>
                    <form id="addTaskForm" class="space-y-4">
                        <div>
                            <label for="taskTitle" class="block text-sm font-medium text-gray-700 mb-1">任务标题</label>
                            <input type="text" id="taskTitle" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200"
                                placeholder="输入任务标题..." required>
                        </div>
                        <div>
                            <label for="taskDescription" class="block text-sm font-medium text-gray-700 mb-1">任务描述</label>
                            <textarea id="taskDescription" rows="3" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200"
                                placeholder="输入任务描述..."></textarea>
                        </div>
                        <div>
                            <label for="taskDueDate" class="block text-sm font-medium text-gray-700 mb-1">截止日期</label>
                            <input type="date" id="taskDueDate" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200">
                        </div>
                        <button type="submit" id="addTaskButton"
                            class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2.5 px-4 rounded-lg transition-all duration-200 transform hover:scale-[1.02] flex items-center justify-center">
                            <i class="fa fa-plus mr-2"></i>添加任务
                        </button>
                    </form>
                </div>

                <!-- 右侧：任务列表区域 -->
                <div class="p-6 md:p-8 w-full md:w-2/3">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-xl font-semibold text-gray-700 flex items-center">
                            <i class="fa fa-tasks text-primary mr-2"></i>任务列表
                        </h2>
                        <div class="flex space-x-2">
                            <button id="filterAll" class="filter-btn px-3 py-1 rounded-md text-sm bg-primary text-white">全部</button>
                            <button id="filterActive" class="filter-btn px-3 py-1 rounded-md text-sm bg-gray-100 hover:bg-gray-200">未完成</button>
                            <button id="filterCompleted" class="filter-btn px-3 py-1 rounded-md text-sm bg-gray-100 hover:bg-gray-200">已完成</button>
                        </div>
                    </div>

                    <!-- 任务统计 -->
                    <div class="bg-gray-50 rounded-lg p-4 mb-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm text-gray-500">总任务数</p>
                                <p class="text-2xl font-bold text-gray-800" id="totalTasks">0</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">已完成</p>
                                <p class="text-2xl font-bold text-green-500" id="completedTasks">0</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">未完成</p>
                                <p class="text-2xl font-bold text-accent" id="pendingTasks">0</p>
                            </div>
                        </div>
                    </div>

                    <!-- 任务列表 -->
                    <div id="taskList" class="space-y-3 max-h-[calc(100vh-350px)] overflow-y-auto pr-2">
                        <!-- 任务项会通过JavaScript动态添加 -->
                        <div class="text-center text-gray-400 py-10" id="emptyTaskList">
                            <i class="fa fa-inbox text-4xl mb-3 block"></i>
                            <p>暂无任务，请添加新任务</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <footer class="w-full py-4 px-4 md:px-8 bg-white/80 backdrop-blur-sm shadow-inner">
        <div class="max-w-6xl mx-auto text-center text-sm text-gray-500">
            <p>© 2025 待办事项管理应用 | 保持高效，轻松生活</p>
        </div>
    </footer>

    <script>
        // 任务数据存储
        // let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
        let tasks = [];
        async function fetchData() {
            var response = await fetch('http://localhost:8080/todo');
            tasks = await response.json();
        }
        let currentFilter = 'all';

        // DOM元素
        const addTaskForm = document.getElementById('addTaskForm');
        const taskList = document.getElementById('taskList');
        const emptyTaskList = document.getElementById('emptyTaskList');
        const totalTasksElement = document.getElementById('totalTasks');
        const completedTasksElement = document.getElementById('completedTasks');
        const pendingTasksElement = document.getElementById('pendingTasks');
        const filterButtons = document.querySelectorAll('.filter-btn');
        const addTaskButton = document.getElementById('addTaskButton');

        // 初始化
        document.addEventListener('DOMContentLoaded', async () => {
            await fetchData();
            renderTasks();
            updateTaskStats();

            // 过滤按钮事件
            document.getElementById('filterAll').addEventListener('click', () => setFilter('all'));
            document.getElementById('filterActive').addEventListener('click', () => setFilter('active'));
            document.getElementById('filterCompleted').addEventListener('click', () => setFilter('completed'));

            // 添加任务表单提交
            addTaskForm.addEventListener('submit', (e) => {
                e.preventDefault();
                addTask();
            });

            // 添加按钮点击事件（额外绑定确保兼容性）
            addTaskButton.addEventListener('click', (e) => {
                e.preventDefault();
                addTask();
            });
            console.log('DOMContentLoaded');
        });

        // 设置过滤器
        function setFilter(filter) {
            currentFilter = filter;
            filterButtons.forEach(btn => {
                btn.classList.remove('bg-primary', 'text-white');
                btn.classList.add('bg-gray-100', 'hover:bg-gray-200');
            });
            
            const activeBtn = document.getElementById(`filter${filter.charAt(0).toUpperCase() + filter.slice(1)}`);
            activeBtn.classList.remove('bg-gray-100', 'hover:bg-gray-200');
            activeBtn.classList.add('bg-primary', 'text-white');
            
            renderTasks();
        }

        // 添加新任务
        async function addTask() {
            const title = document.getElementById('taskTitle').value.trim();
            const description = document.getElementById('taskDescription').value.trim();
            const due_date = document.getElementById('taskDueDate').value;

            if (!title) return;

            const newTask = {
                title,
                description,
                due_date
            };

            await fetch('http://localhost:8080/todo', {
                method: 'POST', // 指定请求方法
                headers: {
                    'Content-Type': 'application/json', // 声明请求体格式
                },
                body: JSON.stringify(newTask)
            });

            await fetchData();
            renderTasks();
            updateTaskStats();

            // 重置表单
            addTaskForm.reset();

            // 添加成功动画效果
            addTaskButton.classList.add('bg-green-500');
            setTimeout(() => {
                addTaskButton.classList.remove('bg-green-500');
            }, 300);
        }

        // 切换任务完成状态
        async function toggleTaskStatus(taskId) {
            await fetch('http://localhost:8080/todo/' + taskId, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                }});
            await fetchData();
            renderTasks();
            updateTaskStats();
        }

        // 删除任务
        function deleteTask(taskId) {
            if (confirm('确定要删除这个任务吗？')) {
                fetch('http://localhost:8080/todo/' + taskId, {
                    method: 'DELETE',
                }).then(async () => {
                    await fetchData();
                    renderTasks();
                    updateTaskStats();
                });

            }
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '无';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
        }

        // 更新任务统计
        function updateTaskStats() {
            const total = tasks.length;
            const completed = tasks.filter(task => task.completed).length;
            const pending = total - completed;
            
            totalTasksElement.textContent = total;
            completedTasksElement.textContent = completed;
            pendingTasksElement.textContent = pending;
        }

        // 渲染任务列表
        function renderTasks() {
            // 过滤任务
            let filteredTasks = [...tasks];
            if (currentFilter === 'active') {
                filteredTasks = tasks.filter(task => !task.completed);
            } else if (currentFilter === 'completed') {
                filteredTasks = tasks.filter(task => task.completed);
            }
            
            // 清空列表
            taskList.innerHTML = '';
            
            // 检查是否有任务
            if (filteredTasks.length === 0) {
                taskList.appendChild(emptyTaskList);
                return;
            }
            
            // 添加任务项
            filteredTasks.forEach(task => {
                const taskElement = document.createElement('div');
                taskElement.className = `task-item p-4 bg-white rounded-lg shadow-sm border-l-4 ${task.completed ? 'border-green-500' : 'border-primary'} transition-all duration-200 hover:shadow-md`;
                
                // 任务项内容
                taskElement.innerHTML = `
                    <div class="flex justify-between items-start">
                        <div class="flex-1 min-w-0">
                            <div class="flex items-start">
                                <input type="checkbox" id="task-${task.id}" ${task.completed ? 'checked' : ''} 
                                    class="mt-1 h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded cursor-pointer transition-colors">
                                <label for="task-${task.id}" class="ml-3 block text-sm font-medium text-gray-700 ${task.completed ? 'task-complete' : 'task-incomplete'}">
                                    ${task.title}
                                </label>
                            </div>
                            ${task.description ? `
                                <p class="mt-1 text-sm text-gray-500 ${task.completed ? 'task-complete' : ''}">
                                    ${task.description}
                                </p>
                            ` : ''}
                            <div class="mt-2 flex items-center text-xs text-gray-500">
                                <span class="flex items-center mr-3">
                                    <i class="fa fa-calendar-o mr-1 ${task.completed ? 'text-gray-400' : 'text-primary'}"></i>
                                    ${formatDate(task.due_date)}
                                </span>
                                <span class="flex items-center">
                                    <i class="fa fa-clock-o mr-1 ${task.completed ? 'text-gray-400' : 'text-primary'}"></i>
                                    ${formatDate(task.created_at)}
                                </span>
                            </div>
                        </div>
                        <div class="ml-4 flex-shrink-0 flex">
                            <button onclick="deleteTask('${task.id}')" class="text-gray-400 hover:text-gray-600 focus:outline-none">
                                <span class="sr-only">删除任务</span>
                                <i class="fa fa-trash-o text-lg"></i>
                            </button>
                        </div>
                    </div>
                `;
                
                // 添加复选框事件
                const checkbox = taskElement.querySelector(`#task-${task.id}`);
                checkbox.addEventListener('change', () => toggleTaskStatus(task.id));
                
                taskList.appendChild(taskElement);
            });
        }
    </script>
</body>
</html>